<?php

namespace app\index\controller;

use ba\Tree;
use think\facade\View;
use Throwable;
use think\facade\Db;
use think\facade\Cookie;
use think\facade\Config;
use app\common\controller\Frontend;

class Index extends Frontend {
    protected array $noNeedLogin = ['index', 'login', 'register', 'logout'];

    public function initialize(): void {
        parent::initialize();
    }

    /**
     * 前台和会员中心的初始化请求
     * @throws Throwable
     */
    public function index(){
        $category = [
            [
                'id' => 1,
                'name' => __('零件') . '/' . __('原材料'),
                'list' => [
                    ['name' => '阿里巴巴（中国）网络技术有限公司', 'type' => 'type', 'area' => 'area', 'cover' => '/static/index/images/pic1.jpg', 'reg_time' => '2024年5月8日', 'person' => 'person', 'reg_money' => 'reg_money'],
                    ['name' => '阿里巴巴（中国）网络技术有限公司', 'type' => 'type', 'area' => 'area', 'cover' => '/static/index/images/pic1.jpg', 'reg_time' => '2024年5月8日', 'person' => 'person', 'reg_money' => 'reg_money'],
                    ['name' => '阿里巴巴（中国）网络技术有限公司', 'type' => 'type', 'area' => 'area', 'cover' => '/static/index/images/pic1.jpg', 'reg_time' => '2024年5月8日', 'person' => 'person', 'reg_money' => 'reg_money'],
                    ['name' => '阿里巴巴（中国）网络技术有限公司', 'type' => 'type', 'area' => 'area', 'cover' => '/static/index/images/pic1.jpg', 'reg_time' => '2024年5月8日', 'person' => 'person', 'reg_money' => 'reg_money'],
                    ['name' => '阿里巴巴（中国）网络技术有限公司', 'type' => 'type', 'area' => 'area', 'cover' => '/static/index/images/pic1.jpg', 'reg_time' => '2024年5月8日', 'person' => 'person', 'reg_money' => 'reg_money'],
                ],
            ],
            [
                'id' => 2,
                'name' => __('组装') . '/' . __('加工'),
                'list' => [

                ]
            ],
            [
                'id' => 3,
                'name' => __('企业服务'),
                'list' => [

                ]
            ],
        ];

        $proposal = [
            ['title' => 'AI智能匹配供货商', 'image' => '/static/index/images/pic1.jpg', 'desc' => 'LINKSC致力于为企业采购的每一个产品，提供海量供货商的数据集中和分析，通过AI智能匹配供货商挑选最合适的供货商。'],
            ['title' => '对比供货商价格', 'image' => '/static/index/images/pic2.jpg', 'desc' => '使用LINKSC的供货商竞价系统，提供3~5个及以上供货商的报价，对比供货商报价作为参考选择产品渠道。'],
            ['title' => '提供一站式服务', 'image' => '/static/index/images/pic3.jpg', 'desc' => 'LINKSC提供全程业务支持。从匹配供货商，对比价格，签合同，售后处理等。贯穿整个采购流程我们始终与您一起。'],
            ['title' => '售后保障制度', 'image' => '/static/index/images/pic4.jpg', 'desc' => 'LINKSC合作的供货商涵盖全国各产业领先的企业。他们正在和三星, LG, SONY, FOXCONN等全世界最大型的企业合作。与LINKSC合作若出现品质问题可凭标准合同和认证书进行产品的更换和赔偿。']
        ];

        View::assign([
            'category' => $category,
            'proposal' => $proposal
        ]);
        return View::fetch();
    }

    public function login(){
        if($this->request->isPost()){
            $params = $this->request->param();

            if(empty($params['account'])) $this->error(__('请输入登录账号'));
            if(empty($params['password'])) $this->error(__('请输入登录密码'));


            $user = db::name('user')->where(['email' => $params['account']])->find();
            if(!$user){
                $user = db::name('user')->where(['tel' => $params['account']])->find();
            }
            if($user){

                if($params['password'] == $user['password']){

                    try{
                        $login_token = bin2hex(random_bytes(32));
                        $cookie_name = 'login_token';
                        $cookie_value = $login_token;
                        $cookie_expiry = time() + (86400 * 30); // 设置过期时间为30天
                        setcookie($cookie_name, $cookie_value, $cookie_expiry, '/', '', false, true);
                        session('login', true);
                        db::name('user')->where(['id' => $user['id']])->update(['token' => $login_token]);
                    }catch (\Exception $e){
                        $this->error($e->getMessage());
                    }

                    $this->success();
                }else{
                    $this->error(__('密码错误'));
                }
            }else{
                $this->error(__('账号不存在'));
            }

            print_r($params);die;
        }
        return View::fetch();
    }
    public function register(){
        if($this->request->isPost()){
            $params = $this->request->param();
            if(empty(trim($params['email']))) $this->error(__('请输入电子邮箱'));
            if(empty($params['password'])) $this->error(__('请输入登录密码'));
            if(empty($params['repassword'])) $this->error(__('请确认密码'));
            if($params['password'] != $params['repassword']) $this->error(__("两次密码输入不一致"));
            if(empty($params['checkbox'])) $this->error('请勾选已阅读并同意《服务条款》和《隐私政策》');

            $params['email'] = trim($params['email']);
            $params['tel'] = empty($params['tel']) ? null : trim($params['tel']);

            $user = db::name('user')->where(['email' => $params['email']])->find();
            if($user) $this->error(__('该邮箱已被注册'));
            if(!empty($params['tel'])){
                $user = db::name('user')->where(['tel' => $params['tel']])->find();
                if($user) $this->error(__('该手机号码已被注册'));
            }




            $login_token = bin2hex(random_bytes(32));
            $cookie_name = 'login_token';
            $cookie_value = $login_token;
            $cookie_expiry = time() + (86400 * 30); // 设置过期时间为30天
            setcookie($cookie_name, $cookie_value, $cookie_expiry, '/', '', false, true);
            session('login', true);
            $insert = [
                'name' => $params['name'],
                'nickname' => '',
                'email' => $params['email'],
                'tel' => $params['tel'],
                'password' => $params['password'],
                'create_time' => $this->timestamp,
                'token' => $login_token
            ];
            $res = db::name('user')->insert($insert);

            $this->success();

        }

        return View::fetch();
    }


    public function logout(){
        $token = Cookie::get('login_token');
        Cookie::delete('login_token');
        db::name('user')->where(['token' => $token])->update(['token' => null]);
        header("location: /");
        die;
    }

}